package com.atguigu.admin.controller;

import com.atguigu.admin.bean.User;
import com.atguigu.admin.service.UserService;
import com.atguigu.admin.utils.SpringUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author Chen Yaqi
 * @version 1.0
 */
@Controller
public class IndexController {

    @Autowired
    UserService userService;


    /**
     * 来登录页面
     *
     * @return 登录页
     */
    @GetMapping({"/", "login"})
    public String loginPage() {
        return "login";
    }

    /**
     * 登录进主页面
     *
     * @param user 用户
     * @return 主页面
     */
    @PostMapping("/login")
    public String index(User user, HttpSession httpSession, Model model,
                        @RequestParam(value = "remember-me", defaultValue = "false") String re,
                        @RequestParam("inputKaptcha") String inputKaptcha,
                        HttpServletResponse response,
                        HttpServletRequest request,
                        RedirectAttributes ra) {

        // 从Session域中获取之前保存的验证码
        String kaptcha = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        // 回传用户名
        ra.addFlashAttribute("username",user.getUsername());
        if (kaptcha == null) {
            ra.addFlashAttribute("msg", "验证码已失效！");
            return "redirect:/";
        }
        if (!kaptcha.equals(inputKaptcha)) {
            ra.addFlashAttribute("msg", "验证码不正确！");
            return "redirect:/";
        }

        // 检查用户密码
        User rightUser = userService.getUserByUsername(user.getUsername());
        if (user.getPassword().equals(rightUser.getPassword())) {
            // 把登录成功的用户保存起来
            httpSession.setAttribute("loginUser", user);
            // 利用Cookie实现密码保存
            if (re.equals("true")) {
                // 保存用户名
                Cookie ckUsername = new Cookie("nms_username", user.getUsername());
                ckUsername.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(ckUsername);
                // 保存密码
                Cookie ckPassword = new Cookie("nms_password", user.getPassword());
                ckPassword.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(ckPassword);
                // 保存选中框
                Cookie ckRemember = new Cookie("nms_remember", "1");
                ckRemember.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(ckRemember);
            } else {
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if ("nms_username".equals(cookie.getName()) || "nms_password".equals(cookie.getName())
                                || "nms_remember".equals(cookie.getName())) {
                            cookie.setMaxAge(0);
                            response.addCookie(cookie);
                        }
                    }
                }
            }
            // 登录成功，重定向到主页面，解决表单重复提交问题
            return "redirect:/index.html";
        } else {
            ra.addFlashAttribute("msg", "账号或密码错误");
            return "redirect:/";
        }
    }

    // 进主页面
    @GetMapping("/index.html")
    public String indexPage(HttpSession httpSession, Model model) {
        // 判断是否登录
        Object loginUser = httpSession.getAttribute("loginUser");
        if (loginUser != null) {
            // 去主页面
            return "index";
        } else {
            model.addAttribute("msg", "账户未登录！");
            return "login";
        }
    }

    // 注册页面
    @GetMapping("/registration")
    public String registrationPage() {
        return "registration";
    }

    // 注册功能
    @PostMapping("/register")
    public String register(User user, RedirectAttributes ra,
                           @RequestParam("inputKaptcha") String inputKaptcha,
                           HttpServletRequest request,
                           Model model) {
        // 从Session域中获取之前保存的验证码
        String kaptcha = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        // 回传用户名
        ra.addFlashAttribute("username",user.getUsername());
        // 回传验证码
        ra.addFlashAttribute("email",user.getEmail());
        // 回传性别
        if (user.getGender().equals("男")){
            ra.addFlashAttribute("gender0","checked");
        } else {
            ra.addFlashAttribute("gender1","checked");
        }
        // 判断验证码
        if (kaptcha == null) {
            // 密码
            ra.addFlashAttribute("password",user.getPassword());
            ra.addFlashAttribute("msg", "验证码已失效！");
            return "redirect:/registration";
        }
        if (!kaptcha.equals(inputKaptcha)) {
            // 密码
            ra.addFlashAttribute("password",user.getPassword());
            ra.addFlashAttribute("msg", "验证码不正确！");
            return "redirect:/registration";
        }
        // 判断用户是否已存在
        User existUser = userService.getUserByUsername(user.getUsername());
        if (existUser != null && existUser.getUsername().equals(user.getUsername())) {
            ra.addFlashAttribute("msg", "已存在此用户！");
            return "redirect:/registration";
        }
        userService.save(user);
        return "redirect:/";
    }

    // log out退出登录功能
    @GetMapping("/user/logOut")
    public String logOut(HttpSession httpSession) {
        // 清除session
        httpSession.removeAttribute("loginUser");
        // 回到登录页
        return "redirect:/";
    }

    // 验证码功能
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        Producer producer = (Producer)SpringUtil.getBean("producer");

        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存到验证码到 session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }
}
